/*
 * Copyright (C) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import fs from '@ohos.file.fs';
import SPLogger from '../utils/SPLogger'
import zlib from "@ohos.zlib"
import { FileBuffer } from '../entity/UploadEntity'
import { csvTIndexInfo } from './CSVUtils';
import GlobalContext from '../../common/utils/globalContext'
import database from "../database/DatabaseUtils";

const globalContext = GlobalContext.getInstance()

/**
 * create file by path
 * @param path
 * @param data
 */
const TAG = "IOUtils"

export function createFilePath(path: string, data: string, dbTime: string) {
    SPLogger.INFO(TAG, "createFilePath called:" + path);
    let writer
    try {
        fs.mkdirSync(globalThis.abilityContext.getApplicationContext().filesDir + "/" + dbTime)
    } catch (err) {
        SPLogger.INFO(TAG, "createFilePath:mkdirSync" + err);
    }

    try {
        // writer = fs.openSync(path, 0o102, 0o666);
        writer = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
        fs.writeSync(writer.fd, data);
        SPLogger.INFO(TAG, "createFilePath:WRITER SUCCESS");
    } catch (err) {
        SPLogger.INFO(TAG, "createFilePath:err" + err);
    } finally {
        fs.closeSync(writer);
    }
}

export async function copyAndZipFile(src: string, dest: string, dirName: string, taskId: string) {
    // src = globalContext.abilityContext.getApplicationContext().filesDir + "/" + globalContext.dbTime
    SPLogger.INFO(TAG, "copyAndZipFile called:, src: " + src + " dest " + dest + " zipName: " + dirName);
    try {
        fs.mkdirSync(dest.toString())
    } catch (err) {
        SPLogger.INFO(TAG, "createFilePath:mkdirSync" + err);
    }

    try {
        SPLogger.INFO(TAG, "copyFileSync start ");
        fs.copyFileSync(src + "/t_index_info.csv", dest + "/IndexInfo.csv");
        fs.copyFileSync(src + "/t_general_info.csv", dest + "/GeneralInfo.csv")

        fs.copyFileSync(src + "/t_scene_info.csv", dest + "/SceneInfo.csv")
        SPLogger.INFO(TAG, "copyFileSync end ");
        let pathCmpts=src.split('/')
        if (pathCmpts.length>0) {
            let gpuInfoObj=await database.queryGPUCounterCSVFileInfo(pathCmpts[pathCmpts.length-1])
            let csvfilename:string=gpuInfoObj['csvFileName']
            if (csvfilename && csvfilename.length>0) {
                fs.copyFileSync(src + "/" + csvfilename, dest + "/GpuCounter.csv")
            }
        }
        let inFile = dest;
        let outFile = dest + ".zip";
        let options = {
            level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION,
            memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT,
            strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY
        };


        return zlib.compressFile(inFile, outFile, options).then(() => {
            SPLogger.INFO(TAG, "zip:end");
            return true;
        }).catch(errData => {
            console.log(`errData is errCode:${errData.code}  message:${errData.message}`);
            return false;
        })
    } catch (err) {
        SPLogger.INFO(TAG, "createFilePath:err" + err);
        return false;
    }
}


export async function createFileZip(input: string, outPath: string): Promise<string> {
    SPLogger.DEBUG(TAG, "createFileZip:called ");
    return await zlib.zipFile(input, outPath, {}).then(res => {
        return outPath
    })
}

export function createFileBuffer(path: string): FileBuffer {
    SPLogger.DEBUG(TAG, "createFileBuffer:called path:" + path);
    let buffer: ArrayBuffer = new ArrayBuffer(4096)
    try {
        let ss = fs.createStreamSync(path, "r+");
        SPLogger.DEBUG(TAG, "createFileBuffer:called createStreamSync:" + ss);
        let num = ss.readSync(buffer)
        if (num > 0) {
            SPLogger.DEBUG(TAG, "createFileBuffer:length" + num);
            return new FileBuffer(buffer, num)
        }
    } catch (err) {
        SPLogger.ERROR(TAG, "createFileBuffer:err:" + err);
    }
    return null
}




